import { observable, action, computed, toJS } from 'mobx';
import { message, Modal } from 'antd';
import * as api from '../../apis/plan/planReportViewApi';
import { WeaTableNew } from 'comsMobx';
import { WeaDatePicker, WeaInput, WeaTextarea, WeaInputNumber, WeaLocaleProvider } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
const getUserLanguage = WeaLocaleProvider.getUserLanguage;
import * as Util from '../../util/Util';
const { TableStore } = WeaTableNew;
const confirm = Modal.confirm;

export default class PlanViewStore {
    @observable loading=false
    @observable cubeLoading=false
    @observable tabDatas = []; //顶部tabdatas
    @computed get tabDatasLength() {
        return this.tabDatas.length;
    }
    @observable userLanguage = ''
    @observable noDataMessage = ''
    @observable tabSelectKey = '1'
    @observable tabKey = '1'
    @observable year = ""
    @observable type1 = ""
    @observable type2 = ""
    @observable planname = ""

    @observable resourceid = ""
    @observable resourcename = ""
    @observable yearDatas = []

    @observable monthWeekSelectComDisplayKey = '' //是否显示日期组件的详情框
    @observable locationkey = ''

    @observable fileids = ''
    @observable filearry = []
    @computed get fileNum(){
        return  this.filearry?this.filearry.length:0
    }

    @observable alinks= []
    @observable auditList = []
    @observable auditids = ''
    @observable shareidsList = []
    @observable canaudit = false
    @observable candel = false
    @observable canedit = false
    @observable canreset = false
    @observable category = ""
    @observable createtask = false
    @observable currentmonth = 1
    @observable editshare = false
    @observable enddate = ""
    @observable fblist = []
    @observable ismonth = 1
    @observable isperformance = false
    @observable isweek = 1
    @observable maxsize = "0"
    @observable planid = ""
    @observable planlist = []
    @observable planmap = {}
    @observable planstatus = "0"
    @observable programid = ""
    @observable remark = ""
    @observable feedback = ''
    @observable summaryin = []
    @observable summarymap = {}
    @observable summaryout = []
    @observable summaryColumns = []
    @observable planColumns = []
    @observable planstatusname = {
        "0": getLabel('509106', '草 稿'),
        "1": getLabel('19134', '审批中'),
        "2": getLabel('509108', '退 回'),
        "3": getLabel('23774', '已完成'),
        "6": getLabel('382750', '已过期'),
    }

    //操作日志
    @observable planLog = {
        datas: [],
        lastcount: 0,
        lastid: '',
        status: '',
    };


    @observable tabDatas = []

    @observable userLanguage = 7

    //共享
    @observable shareTableStore = new TableStore(); // 
    @observable shareConditioninfo = [];

    //建模
    @observable cubeLayoutParame = {};//装载布局请求入参
    @observable Card = {};
    @observable templateResourceId = '';
    @observable templateResourceType = '';
    @observable iscube= ''//是否开启建模
    @observable summaryEcmeTableId = ''
    @observable planEcmeTableId = ''

    //是否显示总结和计划
    @observable isshowsummary=''
    @observable isshowplan=''

    @computed get summaryTableData() {
        if (this.summaryin && this.summaryout) {
            return this.summaryin.concat(this.summaryout)
        } else {
            return []
        }
    }
    @computed get summaryinIds() {
        if (this.summaryin) {
            return this.summaryin.map(s => {
                return s.id
            })
        }
        return []
    }
    @computed get summaryoutIds() {
        if (this.summaryout) {
            return this.summaryout.map(s => {
                return s.id
            })
        }
        return []
    }
    @computed get planIds() {
        if (this.planlist) {
            return this.planlist.map(s => {
                return s.id
            })
        }
        return []
    }

    @computed get summaryInCantEditFields() {
        if (this.summarymap && this.summarymap.list) {
            return this.summarymap.list.map(l => {
                if (!l.detailedit) {
                    return l.fieldname
                }
            })
        }
        return []
    }

    //是否是未保存状态
    @computed get isSaved() {
        return this.planstatus && this.planstatus != ""
    }
    //建模type
    @computed get cubeResourceType(){
        return this.tabSelectKey+""+this.templateResourceType
    }

    @action
    setValue = (param, value) => {
        this[param] = value
    }

    @action("获取计划内容")
    getPlanView = (params) => {
        this.loading = true;
        if (!params) {
            params = {};
            params.type1 = this.tabSelectKey == '1' ? '1' : '2';
            params.type2 = this.type2
            params.year = this.year;
            params.resourceid = this.resourceid;
            params.resourcetype = this.resourcetype;
        }
        this.locationkey = new Date().getTime()*Number(Math.random().toFixed(2))
        api.getPlanDetail(params).then(
            action("getPlanViewSuccess", res => {
                this.resetFields()
                this.loading = false;
                this.locationkey = new Date().getTime()*Number(Math.random().toFixed(2))
                this.tabDatas = res.tabDatas
                this.year = res.year ? res.year : new Date().getFullYear()
                this.type1 = res.type1
                this.type2 = res.type2
                this.tabSelectKey = res.type1
                this.resourceid = res.resourceid
                this.resourcename = res.resourcename
                this.enddate = res.enddate
                this.ismonth = res.ismonth
                this.isweek = res.isweek
                this.summaryEcmeTableId = res.summaryEcmeTableId
                this.planEcmeTableId = res.planEcmeTableId

                if(this.type1=='1' && Number(this.type2) >12){
                    this.type2 = new Date().getMonth()+1
                }
                this.userLanguage = res.userLanguage
                if (res.api_status == '1') {
                    this.planstatus = res.planstatus
                    this.alinks = res.alinks?res.alinks:[]
                    this.tabSelectKey = res.type1
                    this.planid = res.planid
                    this.fileids = res.fileids?res.fileids:''
                    this.filearry = res.filearry
                    this.planname = res.planname
                    this.auditList = res.auditList?res.auditList:[]
                    this.auditids = res.auditids?res.auditids:''
                    this.summarymap = res.summarymap
                    this.planmap = res.planmap
                    this.planlist = res.planlist
                    this.addTempIdToPlanList()
                    this.programid = res.programid
                    this.summaryin = res.summaryin ? res.summaryin : []
                    this.summaryout = res.summaryout ? res.summaryout : []
                    this.canaudit = res.canaudit
                    this.candel = res.candel
                    this.canedit = res.canedit
                    this.canreset = res.canreset
                    this.category = res.category
                    this.maxsize = res.maxsize
                    this.createtask = res.createtask
                    this.isperformance = res.isperformance
                    this.editshare = res.editshare
                    this.fblist = res.fblist
                    this.shareidsList = res.shareidsList
                    this.summaryColumns = this.buildTableColumns(res.summarymap)
                    this.planColumns = this.buildTableColumns(res.planmap, true)
                    this.buildSummaryData()
                    this.planid && this.getPlanLog()
                    this.noDataMessage = ''
                    this.remark = res.remark
                    this.isshowplan=res.isshowplan
                    this.isshowsummary=res.isshowsummary
                    this.templateResourceId=res.templateResourceId?res.templateResourceId:''
                    this.templateResourceType=res.templateResourceType?res.templateResourceType:''
                    this.iscube=res.iscube
                    this.tabKey=="1"&&this.initForm({planid:this.planid,partType:this.cubeResourceType,partId:this.templateResourceId})
                } else {
                    this.noDataMessage = res.api_status
                    this.planname = res.planname
                }
                if (!this.planname) {
                    this.planname = this.getPlanName(this.resourcename)
                }
                //this.getShareSearch()
            }),
            action("getPlanViewError", error => {
                this.resetFields()
                this.noDataMessage = error.api_status
                this.loading = false;
                this.locationkey = new Date().getTime()
                if (!this.planname) {
                    this.planname = this.getPlanName(this.resourcename)
                }
            })
        )
    }

    @action("给planlist的默认数据加零时id")
    addTempIdToPlanList() {
        this.planlist = this.planlist.map((p, i) => {
            if (!p.id) {
                p.id = 'temp' + new Date().getTime() + i
            }
            return p
        })
    }

    //设置工作计划标题
    getPlanName = (resourcename) => {
        //杨文元2019年28周工作总结及2019年29周工作计划
        let { year, type1, type2 } = this;
        let nextYear = (type1 == 1 && type2 == 12) ? parseInt(year) + 1 : year;
        let nextMonth = (type1 == 1 && type2 == 12) ? 1 : (parseInt(type2) + 1);
        let monthOrWeekValue = this.tabSelectKey == '1' ? type2 + '月' : type2 + '周'
        let nextMonthOrWeekValue = this.tabSelectKey == '1' ? nextMonth + '月' : parseInt(type2) + 1 + '周'

        let planname = ''
        if (this.userLanguage == "8") {
            monthOrWeekValue = this.tabSelectKey == '1' ? "month " + type2 : "week " + type2
            nextMonthOrWeekValue = this.tabSelectKey == '1' ? "month " + nextMonth : "week " + parseInt(type2) + 1
            planname = `${resourcename}${year}-${monthOrWeekValue} work summary and ${nextYear}-${nextMonthOrWeekValue} work plan`
        } else {
            planname = `${resourcename}${year}年${monthOrWeekValue}工作总结及${nextYear}年${nextMonthOrWeekValue}工作计划`
        }

        return planname;
    };
    @action("reset")
    resetFields = () => {
        this.tabDatas = []; //顶部tabdatas
        this.planname = ""

        this.resourceid = ""
        this.resourcename = ""
        this.yearDatas = []
        this.getYearSelectoption()
        this.monthWeekSelectComDisplayKey = '' //是否显示日期组件的详情框
        this.locationkey = ''

        this.alinks=[]
        this.fileids = ''
        this.filearry = []
        this.auditList = []
        this.auditids=''
        this.shareidsList = []
        this.canaudit = false
        this.candel = false
        this.canedit = false
        this.canreset = false
        this.category = ""
        this.createtask = false
        this.currentmonth = 1
        this.editshare = false
        this.enddate = ""
        this.fblist = []
        this.ismonth = 1
        this.isperformance = false
        this.isweek = 1
        this.maxsize = ""
        this.planid = ""
        this.planlist = []
        this.planmap = {}
        this.planstatus = ""
        this.programid = ""
        this.remark = ""
        this.summaryin = []
        this.summarymap = {}
        this.summaryout = []
        this.summaryColumns = []
        this.planColumns = []
        this.planLog = {
            datas: [],
            lastcount: 0,
            lastid: '',
            status: '',
            logType: 'noView',
        };
        this.isshowsummary=''
        this.isshowplan=''
        this.templateResourceId=''
        this.templateResourceType=''
        this.iscube=''
        this.summaryEcmeTableId=""
        this.planEcmeTableId=""
    }

    @action("周报月报切换")
    tabChange = (e) => {
        this.tabSelectKey = e
        this.year = new Date().getFullYear()
        this.type1 = e
        this.type2 = ''
        this.getPlanView()
        this.resetTabKey()
    }
    //获取年份选择框
    @action getYearSelectoption = () => {
        if (this.yearDatas.length < 1) {
            return this.initYearDateSelectOptions();
        }
        return this.yearDatas;
    };

    //初始化年份选择框
    @action initYearDateSelectOptions = () => {
        let currentYear = parseInt(new Date().getFullYear());
        let yearList = [];
        for (var i = currentYear; i > currentYear - 6; i--) {
            yearList.push({ showname: i, key: i });
        }
        this.yearDatas = yearList;
    };
    //日期变动事件
    @action onDateChange = (param, v, isRefresh) => {
        this[param] = v;
        if (!isRefresh) {
            this.getPlanView();
        }
        this.tabKey='1'
        this.monthWeekSelectComDisplayKey = 'none'
        this.locationkey = new Date().getTime()
    };
    @action toggleMonthWeekSelectComDisplayKey = () => {
        this.locationkey = new Date().getTime();
        this.monthWeekSelectComDisplayKey = 'none';
    }
    @action("根据字段设置总结的表头")
    buildTableColumns = (columnMap, isPlan) => {
        const columnConfigs = columnMap.list;
        if (!columnConfigs || columnConfigs.length < 1) {
            return [];
        }
        let columns = [];
        let totalShowWidth = 0;
        columnConfigs.map(config => {
            totalShowWidth += parseInt(config.showwidth);
        });



        columnConfigs.map((config, i) => {
            let width = parseInt(config.showwidth) / totalShowWidth * 100;
            columns.push({
                title: config.showname,
                dataIndex: config.s_fieldname,
                key: config.s_fieldname,
                width: config.showwidth + '%',
                com: [
                    {
                        type: 'text', //timepicker inputnumber TEXTAREA text
                        key: config.s_fieldname,
                        hasHiddenField: true,
                        defaultValue: '',
                        viewAttr: 2,
                    },
                ],
            });
        });
        return columns;
    }
    @action("处理总结数据")
    buildSummaryData = () => {
        this.summaryin && this.summaryin.length > 0 && this.summaryin.forEach(s => {
            s.planType = '计划内'
        })
        this.summaryout && this.summaryout.length > 0 && this.summaryout.forEach(s => {
            s.planType = '计划外'
        })
    }

    @action("添加计划外")
    addSummaryOut = (v,index) => {
        if(index>-1){
            index = index-this.summaryin.length
            this.summaryout.splice(index + 1, 0, v);
        }else{
            this.summaryout.push(v)
        }
    }
    @action("变动计划")
    planListChange = (v, index) => {
        this.planlist[index] = v
    }
    @action("变动计划外")
    summaryOutChange = (v, index) => {
        this.summaryout[index] = v
        
    }
    @action("变动计划内")
    summaryInChange = (v, index) => {
        this.summaryin[index] = v
    }
    @action("添加计划")
    addPlanList = (v, index) => {
        if ( index > -1) {
            this.planlist.splice(index + 1, 0, v);
        } else {
            this.planlist.push(v)
        }
    }
    doOperation = (operation, doback) => {
        switch (operation) {
            case 'save':
                this.saveOrSubmitPlan('save');
                break;
            case 'del':
                this.deletePlan();
                break;
            case 'submit':
                this.saveOrSubmitPlan('submit');
                break;
            case 'reset':
                this.resetPlan();
                break;
            case 'approve':
                this.auditPlan('approve', doback);
                break;
            case 'return':
                this.auditPlan('return', doback);
                break;
            case 'share':
            default:
                break;
        }
    };
    //审核计划
    auditPlan = (operation, doback) => {
        let params = {};
        params.operation = operation;
        params.planid = this.planid;
        let content = operation == 'approve' ? getLabel('509442', '确认批准吗？') : getLabel('509443', '确认退回吗？');
        let _this = this
        confirm({
            title: getLabel('508972', '确认提示'),
            content: content,
            onOk() {
                _this.loading = true;
                api.auditPlan(params).then(
                    action(data => {
                        _this.loading = false;
                        if (data.api_status == '1') {
                            message.success(getLabel('30700', '操作成功'));
                            _this.getPlanView();


                        } else {
                            message.error(data.message || getLabel('383746', '请求失败'));
                        }
                        //刷新审核列表
                        if (window.opener && typeof window.opener.planAuditRefresh === 'function') {
                            window.opener.planAuditRefresh()
                        }
                        if (window.opener && typeof window.opener.planGetNoAuditCount === 'function') {
                            window.opener.planGetNoAuditCount()
                        }
                        if (doback) {
                            if (typeof doback == 'function') {
                                doback()
                            }
                        }
                    })
                );
            },
            onCancel() { },
        });
    };
    //保存或者提交计划
    @action saveOrSubmitPlan = operation => {
        let paramsData = this.getOperationParams(operation);
        //如果开启建模
        if (this.iscube=='1' && this.Card.Actions) {//建模布局保存方法
            const { ecmeDoSubmit } = this.Card.Actions;
            ecmeDoSubmit().then((data) => {
                let {mainTable} = data.JSONStr
                //主表数据
                paramsData.remark = mainTable.PR_PlanReport?mainTable.PR_PlanReport.remark:"";
                let summaryData = data.JSONStr.detailTable.PR_PlanReportDetail
                let planData = data.JSONStr.detailTable.PR_PlanReportDetail_V
                //计划内数据的id
                let summaryinIds = this.summaryin.map(s=>{
                    return s.id
                })
                if(summaryData && summaryData.length>0){
                    //筛选出计划外数据
                    let summaryoutData = summaryData.filter(d=>{
                        return summaryinIds.indexOf(d.id)<0
                    })
                    let summaryinData = summaryData.filter(d=>{
                        return summaryinIds.indexOf(d.id)>-1
                    })
                    paramsData.summaryout = JSON.stringify(summaryoutData)
                    paramsData.summaryin = JSON.stringify(summaryinData)
                }
                if(planData && planData.length>0){
                    planData.forEach(p=>{
                        if(p.id.startsWith("temp")){
                            p.id=''
                        }
                    })
                    paramsData.planlist = JSON.stringify(planData)
                }
                //额外字段
                paramsData.extendDatas=data.JSONStr.extendDatas
                const {exdetailTable} = data.JSONStr.extendDatas
                if(exdetailTable && exdetailTable[this.summaryEcmeTableId]){
                    paramsData.extendDatas.detail1Ids =  exdetailTable[this.summaryEcmeTableId].map(e=>e.id).join(',')
                }
                if(exdetailTable && exdetailTable[this.planEcmeTableId]){
                    paramsData.extendDatas.detail2Ids =  exdetailTable[this.planEcmeTableId].map(e=>e.id).join(',')
                }
                paramsData.extendDatas = JSON.stringify( paramsData.extendDatas)
                this.doSaveOrSubmit(paramsData,operation,true)
                // if(params.doback){
                //     params.doback(data.JSONStr.mainTable.TM_TaskInfo,1,data.JSONStr.extendDatas);
                //}
            })
        }else{
            this.doSaveOrSubmit(paramsData,operation)
        }

        
    };
    @action doSaveOrSubmit=(paramsData,operation,skipValidate)=>{
        if(!skipValidate){
            let flag = this.checkMust(paramsData);
            if (!flag) {
                message.info(getLabel('509111', '请填写标题不为空的必填项！'));
                return;
            }
        }
        
        this.loading = true;
        api.saveOrSubmitPlan(paramsData).then(
            action(data => {
                if (data.api_status == '1') {
                    //重置计划日志查询条件
                    this.planLog = {
                        datas: [],
                        lastcount: 0,
                        lastid: '',
                        status: '',
                    };
                    this.getPlanView();
                    message.success(operation == 'save' ? getLabel('22619', '保存成功') : getLabel('16248', '提交成功'));
                } else {
                    message.error(data.message || getLabel('383746', '请求失败'));
                }
                this.loading = false;
            })
        );
    }
    //delete plan detail
    @action deletePlan = () => {
        this.loading = true
        let param = {};
        param.planid = this.planid;
        param.year = this.year
        param.resourceid = this.resourceid
        param.type1 = this.type1
        param.type2 = this.type2
        let _this = this
        confirm({
            title: getLabel('508972', '确认提示'),
            content: getLabel('509113', '确认删除此报告吗？'),
            onOk() {
                api.deletePlan(param).then(
                    action(data => {
                        _this.loading = false
                        if (data.api_status == '1') {
                            message.success(getLabel('30700', '操作成功'));
                            _this.resetFields()
                            _this.resetTabKey()
                            _this.getPlanView();

                        } else {
                            message.error(data.message || getLabel('383746', '请求失败'));
                        }
                    })
                );
            },
            onCancel() { },
        });
    };
    //获取操作参数 请求参数
    getOperationParams = operation => {
        let summaryin = toJS(this.summaryin);
        let summaryout = toJS(this.summaryout);
        let planlist = toJS(this.planlist);
        this.removeFieldsNoInColumns(summaryin);
        this.removeFieldsNoInColumns(summaryout);
        this.removeFieldsNoInColumns(planlist);
        return {
            resourceid: this.resourceid,
            planid: this.planid,
            operation: operation,
            // planname: this.getPlanName (this.resData.resourcename),
            planname: this.planname,
            auditids: this.auditids,
            year: this.year,
            type1: this.type1,
            type2: this.type2,
            remark: this.remark,
            programid: this.programid,
            summaryin: JSON.stringify(summaryin),
            summaryout: JSON.stringify(summaryout),
            planlist: JSON.stringify(planlist),
            fileids: this.fileids,
            iscube:Object.keys(toJS(this.cubeLayoutParame)).length > 0?"1":"0"
        };
    };
    //去掉无用的属性
    removeFieldsNoInColumns(data) {
        if (data && data.length > 0) {
            data = data.map(v => {
                delete v['fbdate'];
                delete v['taskarray']
                delete v['filearray']
                delete v['docarray']
                delete v['wfarray']
                delete v['crmarray']
                delete v['projectarray']
                delete v['planType']
                delete v['undefined']
                delete v['s_undefined']
                if (v.id && v.id.startsWith('temp')) {
                    delete v['id'];
                }
                return v;
            });
        }
    }
    //检查必填项
    checkMust = params => {
        let planlist = JSON.parse(params.planlist);
        let summaryoutlist = JSON.parse(params.summaryout);
        let summaryinlist = JSON.parse(params.summaryin);
        let planMapList = this.planmap.list;
        let summaryMapList = this.summarymap.list;
        var flag = true;
        if (planlist && planlist.length > 0) {
            planlist.map(v => {
                for (var k in v) {
                    planMapList.map(p => {
                        if (
                            p['ismust'] == 1 &&
                            (v[p['fieldname']] === '' || v[p['fieldname']] == undefined)
                        ) {
                            flag = false;
                        }
                    });
                }
            });
        }
        if (summaryoutlist && summaryoutlist.length > 0) {
            summaryoutlist.map(v => {
                for (var k in v) {
                    summaryMapList.map(p => {
                        if (p['ismust'] == 1 && !v[p['fieldname']]) {
                            flag = false;
                        }
                    });
                }
            });
        }
        if (summaryinlist && summaryinlist.length > 0) {
            summaryinlist.map(v => {
                for (var k in v) {
                    summaryMapList.map(p => {
                        if (p['ismust'] == 1 && !v[p['fieldname']]) {

                            flag = false;
                        }
                    });
                }
            });
        }

        return flag;
    };
    //保存报告每条计划明细详情
    @action saveDetailView = params => {
        this.loading = true
        api.saveDetailView(params).then(
            action(data => {
                this.loading = false
                if (data.api_status == '1') {
                    if (params.doback) {
                        params.doback(data.plandetailid);
                    }
                }
            })
        );
    };
    @action('获取请求日志')
    getPlanLog = () => {
        this.planLog.planid = this.planid;
        let param = toJS(this.planLog)
        delete param.datas
        api.getPlanLog(param).then(
            action(res => {
                if (res.api_status == '1') {
                    let tempArray = toJS(this.planLog.datas);
                    tempArray.push(...res.datas);
                    this.planLog = res;
                    this.planLog.datas = tempArray;
                } else {
                    message.error(res.message || '接口调用失败！');
                }

            })
        ).catch(res => {
        });
    };
    @action("more plan log")
    morePlanLog = () => {
        if (this.planLog.logType == 'noView') {
            this.planLog.logType = 'all';
            this.planLog.datas = [];
            this.planLog.lastcount = 0;
        }
    }
    //重新编写
    @action resetPlan = () => {
        let param = {};
        param.planid = this.planid;
        let _this = this
        confirm({
            title: getLabel('508972', '确认提示'),
            content: getLabel('509114', '确认重新编写吗？'),
            onOk() {
                api.resetPlan(param).then(
                    action(data => {
                        if (data.api_status == '1') {
                            _this.getPlanView();
                        } else {
                            message.error(data.message || getLabel('383746', '请求失败'));
                        }
                    })
                );
            },
            onCancel() { },
        });
    };
    //save feedback
    @action('添加计划反馈')
    addPlanExchange = () => {
        let param = {};
        param.planid = this.planid;
        param.content = this.feedback
        if (!param.content || (param.content && param.content.length < 1)) {
            message.info(getLabel('383036', '请输入内容'));
            return;
        }
        api.addPlanExchange(param).then(
            action(data => {
                this.feedback = ''
                this.fblist.unshift(data.datas);
            })
        );
    };

    //添加任务
    @action addTask = (param, record) => {
        let _ = this
        api.addTask(param).then(
            action(data => {
                if (data.api_status == '1') {
                    window.open(
                        '/spa/workrelate/static/index.html#/main/workrelate/task/taskDetail?id=' +
                        data.taskId
                    );
                    _.saveOrSubmitPlan('save')
                } else {
                    message.error(data.message || getLabel('383746', '请求失败'));
                }
            })
        );
    };
    //save share
    @action('设置分享人')
    setPlanShare = (ids, sharedatas) => {

        this.loading = true;
        let param = {};
        param.planid = this.planid;
        param.shareids = ids;
        api.setPlanShare(param).then(action(data => {
            this.planLog.datas.unshift(data.datas);
            this.shareidsList = sharedatas;
            this.loading = false;
        })
        );
    };
    @action("上传附件改变事件")
    onUploadChange = (ids, list) => {
        this.uploadReset = false
        // this.loading = true
        if (ids.length > 0) {
            let newAddFileids = '';
            for (let i = 0; i < list.length; i++) {
                let fileA = {};
                if (!this.fileids) this.fileids = ''
                if (!this.filearry) this.filearry = []
                if (this.fileids.indexOf(',' + ids[i] + ',') == -1) {
                    newAddFileids += ids[i] + ',';
                    this.fileids += ids[i] + ',';
                    fileA.id = ids[i];
                    fileA.name = list[i].filename;
                    this.filearry.push(fileA);
                }
            }
        }
        // this.loading = false
        this.uploading = false
        this.doOperation('save')
        this.uploadReset = true
    }

    @action('看文档')
    viewDocFiled = params => {
        api.viewDocFiled(params).then(
            action(data => {
                if (data.api_status == '1') {
                    params.doback();
                }
            })
        );
    };

    @action("设置分享查询")
    getShareSearch = () => {
        this.loading = true;
        let params = {
            operate:'search',
            workrelatetype:'4',
            hasRight:this.editshare,
            bizid:this.planid,
            resourceid:this.resourceid
        }
        api.workrelateShare(params).then(action(res => {
            this.loading = false;
            if (res.status) {
                this.shareConditioninfo = res.conditioninfo;
                this.shareTableStore.getDatas(res.datas)
            } else {
                message.error(res.msg || getLabel('508818', '接口调用失败！'))
            }
        }));
    }

    @action("共享新增删除")
    shareOperate = (params) => {
        this.loading = true;
        api.workrelateShare(params).then(action(res => {
            if (res.status) {
                if (!res.hasRight) {
                    message.error(getLabel('2012', '对不起，您暂时没有权限！'));
                } else {
                    message.success(getLabel('30700', '操作成功'));
                    this.getShareSearch();
                    this.getPlanView()
                }
            } else {
                message.error(res.msg || getLabel('508818', '接口调用失败！'))
            }
            this.loading = false;
        }));
    }

    @action
    resetTabKey=()=>{
        this.tabKey='1'
        this.tabSelectKey=this.type1
    }

    //初始化
    @action
    initForm = params => {
        this.cubeLoading=true
        api.getPlanSetupInit(params).then(action((result) => {
            this.cubeLoading=false
            if(result.status==1 && result.isopen === true){
              //  this.cubeLoading=true
                this.cubeLayoutParame = {...result.data};
                if(params.doback){
                    params.doback();
                }
            }
        }));
    }
    @action
    getCardStorefun = (store)=>{
        this.Card = store;
    }


    @action
    dealInitData=()=>{
        let {summaryin,planlist,summaryinIds} = this
        //新建的时候，把planlist的数据和 summarin的数据填充到detailtable里去
        const {allFields} =toJS( this.Card)
        //总结-计划内默认数据
        buildDetailRowData(summaryin,'detail_1')
        //计划默认数据
        buildDetailRowData(planlist,'detail_2')
        function buildDetailRowData(oriList,tableName){
            let detailDataMap = {}
            for(var k in allFields){
                if(allFields[k].detail == tableName){
                    detailDataMap[allFields[k].fieldname] = k
                }
            }
            oriList.forEach(s=>{
                let detailRow  = {}
                for(var k in s){
                    detailRow[detailDataMap[k]]={
                        value:s[k]
                    }
                }
                window.ModeForm.addDetailRow(tableName,detailRow)     
            })
        }
    }


}

